// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
    //   const wxContext = cloud.getWXContext()
    const {
        groupId,
        userId,
        invite = false,
        inviter,
        isLeader
    } = event;
    await db.collection('user').doc(userId).update({
        data: {
            project: db.command.push(groupId),
            master: db.command.push(isLeader ? groupId : null)
        }
    })
    if (invite) {
        //向code中加入成员
        await db.collection('code').add({
            data: {
                code: -1,
                time: new db.serverDate(),
                lat: -1,
                lng: -1,
                userId,
                group: groupId,
                inviter
            }
        })
    }
    if (isLeader) {
        const res = await db.collection('code').where({
            group: groupId,
            userId,
        }).get()
        if (res.data && res.data.length) {
            await db.collection('code').doc(res.data[0]._id).update({
                data: {
                    role: "master"
                }
            })
        }
    }
    return
}